var PeopleMedia = (function ($jq) {
    return {
           Domain: 'peoplemedia.com',
        BaseDomain: 'peoplemedia',
        SiteImagePath: 'http://pmi.peoplemedia.com/',
        SiteRootEnabled: true,
        PersistentLoginEnabled: false,
        PopupPath: '/v3/html/Popup/',
        _adReloadTimeout: null,
        ReloadAds: function () {
            if (PeopleMedia._adReloadTimeout == null) {
                PeopleMedia._adReloadTimeout = setTimeout('PeopleMedia._reloadAds();', 400);
            }
        },
        _reloadAds: function () {
            PeopleMedia._adReloadTimeout = null;
            try {
                $jq('.AdIFrame').each(function () { $jq(this).attr('src', $jq(this).attr('src')); });
                setTimeout('PeopleMedia.RefreshSession', 600);
            }
            catch (e) { }
        },

        RefreshSession: function () {
            if (!PeopleMedia.PersistentLoginEnabled) {
                var startTime = new Date().getTime();
                var url = '/v3/ajax/RefreshSession';
                var timeoutValue = 60000;
                $jq.ajax({
                    type: "GET",
                    url: url,
                    data: {},
                    dataType: "json",
                    success: function (response) {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        if (errorThrown === 'timeout' || (jqXHR.readyState !== 0 && jqXHR.status !== 0)) {
                            var endTime = new Date().getTime();
                            var duration = (endTime - startTime);
                            // PeopleMedia.Popups.ShowGenericMessage(PeopleMedia.Popups.AjaxErrorMessage());
                            PeopleMedia.Logger.LogAjaxErrorXHR("Ajax request failure", url, { method: "PeopleMedia.RefreshSession", duration: duration }, jqXHR, textStatus, errorThrown, function () {
                            });
                        }
                    },
                    async: true,
                    cache: false,
                    timeout: timeoutValue,
                    suppressErrors: true
                });
                PeopleMedia.Timer.StartCountdownTimer();
            }
        }
    };
})(jQuery);

PeopleMedia.CreateComboBox = function(attachment, watermark, styleAttributes){
            jQuery("#" + attachment).combobox();
            var searchBox = jQuery('#'+attachment).next(); 
            searchBox.val(watermark);

            if (styleAttributes != null) {
                searchBox.css(styleAttributes);
            }
                        
        };

PeopleMedia.LogAjaxError = function (event, jqXHR, ajaxSettings, thrownError) {
    if (thrownError != 'timeout' && (jqXHR.readyState == 0 || jqXHR.status == 0)) {
        $jq(document).one('ajaxError', PeopleMedia.LogAjaxError);
        return;
    }
        
        if (ajaxSettings && ajaxSettings.url) {
            if (ajaxSettings.url.indexOf('/v3/log/logexception') >= 0 ||
                ajaxSettings.url.indexOf('/v3/ajax/RefreshSession') >= 0 ||
                ajaxSettings.url.indexOf('/keepalive.cfm') >= 0) {
                    $jq(document).one('ajaxError', PeopleMedia.LogAjaxError);
                    return;
            }
        }

        if (ajaxSettings && ajaxSettings.suppressErrors) {
            $jq(document).one('ajaxError', PeopleMedia.LogAjaxError);
            return;
        }

        PeopleMedia.Popups.ShowGenericMessage(PeopleMedia.Popups.AjaxErrorMessage());
        PeopleMedia.Logger.LogAjaxErrorXHR("Ajax request failure", ajaxSettings.url, { settings: ajaxSettings }, jqXHR, null, thrownError, function () { $jq(document).one('ajaxError', PeopleMedia.LogAjaxError); });
    };
(function () {
    $jq.ajaxSetup({ timeout: 60000 });
    $jq(document).one('ajaxError', PeopleMedia.LogAjaxError);
})();
PeopleMedia.HeaderCounts = new function () {
    this.refreshConnectCount = function (connectTotal, yesvotes, favorites, views) {
        var connectTotalCaption = (connectTotal > 999 ? '999+' : connectTotal);
        $jq('#connectstarburst').empty().html('<p>' + connectTotalCaption + '</p>');
        if (connectTotal > 0) {
            $jq('#connectStarBurstArea').show();
        } else {
            $jq('#connectStarBurstArea').hide();
        }

        if (yesvotes >= 0)
        {
            var yesvotesTotalCaption = "(" + (yesvotes > 999 ? '999+' : yesvotes) + ")";
            if (yesvotes == 0) { yesvotesTotalCaption = ''; }
            $jq('#connect_yesvotes').empty().html(yesvotesTotalCaption);
        }
        
        if (favorites >= 0) {
            var favoritesTotalCaption = "(" + (favorites > 999 ? '999+' : favorites) + ")";
            if (favorites == 0) { favoritesTotalCaption = ''; }
            $jq('#connect_favorites').empty().html(favoritesTotalCaption);
        }

        if (views >= 0) {
            var viewsTotalCaption = "(" + (views > 999 ? '999+' : views) + ")";
            if (views == 0) { viewsTotalCaption = '';}
            $jq('#connect_views').empty().html(viewsTotalCaption);
        }

    };
    this.refreshSubHeaderCounts = function () {
        $jq.ajax({
            type: 'GET',
            url: "/v3/ajax/RefreshSubHeaderCounts",
            success: function (response) {
                if (response.display == true) {
                    $jq('#subheader').html(response.html).fadeIn();
                } else {
                    $jq('#subheader').fadeOut().empty();
                }
            }
        });
    };
};


PeopleMedia.Timer = new function () {
    this.logoutWarningMinutes = 15;
    this.logoutWarningTimer = null;
    this.StartCountdownTimer = function (minutes) {
        if (!PeopleMedia.PersistentLoginEnabled) {
            if (minutes) {
                PeopleMedia.Timer.logoutWarningMinutes = minutes;
            }
            if (PeopleMedia.Timer.logoutWarningTimer) {
                clearTimeout(PeopleMedia.Timer.logoutWarningTimer);
            }

            PeopleMedia.Timer.logoutWarningTimer = setTimeout('PeopleMedia.Timer.ShowLogoutWarning();', PeopleMedia.Timer.logoutWarningMinutes * 60000 - 10000);
        }
    };
    this.autoLogoutInterval = null;
    this.finalCountdown = 0;
    this.ShowLogoutWarning = function () {
        if (!PeopleMedia.PersistentLoginEnabled) {
            var html = '<div class="popupshowtimeout"><div class="overlaywholescreen"></div><div class="overlayplace"><div class="popupshapestyle timeoutwarningoverlay">' +
                '<div class="standardpopupcontent"><h1>Keep it up, there are more great connections waiting for you!<br/>You&rsquo;ve been inactive and will be logged out in <span id="timeBeforeLogoutSpan">5:00</span>.</h1>' +
                    '<p class="popupupgradebtn"><a href="javascript:;" class="button_style PopupOkButton" id="autoLogoutStayLoggedInButton" title="Keep Me Logged In!">Stay Logged In</a>' +
                    '<a href="/v3/logout" class="button_style_gray" title="Log me out">Logout</a></p></div></div></div></div>';
            $jq('#PopupDisplayAreaDiv').html(html);
            $jq('#autoLogoutStayLoggedInButton').click(function () {
                PeopleMedia.Timer.ExtendSession();
                PeopleMedia.Timer.ClosePopup();
            });
            $jq('#PopupDisplayAreaDiv').show();
            PeopleMedia.Timer.autoLogoutInterval = setInterval('PeopleMedia.Timer.UpdateFinalCountdown();', 1000);
            PeopleMedia.Timer.finalCountdown = 300;
        }
    };
    this.AbortLogoutTimer = function () {
        if (!PeopleMedia.PersistentLoginEnabled) {
            if (PeopleMedia.Timer.logoutWarningTimer) {
                clearTimeout(PeopleMedia.Timer.logoutWarningTimer);
                PeopleMedia.Timer.logoutWarningTimer = null;
            } else {
                setTimeout('PeopleMedia.Timer.AbortLogoutTimer();', 5000);
            }
        }
    };
    this.UpdateFinalCountdown = function () {
        if (!PeopleMedia.PersistentLoginEnabled) {
            PeopleMedia.Timer.finalCountdown--;
            if (PeopleMedia.Timer.finalCountdown < 0) {
                clearInterval(PeopleMedia.Timer.autoLogoutInterval);
                PeopleMedia.Timer.Logout();
                return;
            }
            var totalSeconds = PeopleMedia.Timer.finalCountdown;
            var minutes = Math.floor(totalSeconds / 60);
            var seconds = totalSeconds % 60;
            var padding = '';
            if (seconds < 10) {
                padding = '0';
            }
            $jq('#timeBeforeLogoutSpan').html(minutes + ":" + padding + seconds);
        }
    };
    this.Logout = function () {
        location.href = '/v3/logout/';
    };
    this.ClosePopup = function () {
        if (!PeopleMedia.PersistentLoginEnabled) {
            clearInterval(PeopleMedia.Timer.autoLogoutInterval);
            $jq('#PopupDisplayAreaDiv').hide();
            PeopleMedia.RefreshSession();
            PeopleMedia.Timer.StartCountdownTimer();
        } else {
            $jq('#PopupDisplayAreaDiv').hide();
        }
    };
    this.Init = function () {
        if (!PeopleMedia.PersistentLoginEnabled) {
            PeopleMedia.Timer.StartCountdownTimer(15);
        }
    };
    this.sessionMinutesRemaining = 20;
    this.sessionInterval = null;
    this.minutesSinceLastActivity = 0;
    this.ExtendSession = function (totalMinutes) {
        if (!PeopleMedia.PersistentLoginEnabled) {
            if (totalMinutes) {
                sessionMinutesRemaining = totalMinutes;
                PeopleMedia.Timer.StartCountdownTimer(totalMinutes - 5);
            }
            if (PeopleMedia.Timer.sessionInterval == null) {
                PeopleMedia.Timer.sessionInterval = setInterval('PeopleMedia.Timer.ExtendSession();', 60000);
            } else {
                PeopleMedia.Timer.sessionMinutesRemaining--;
                PeopleMedia.Timer.minutesSinceLastActivity++;
                if (PeopleMedia.Timer.minutesSinceLastActivity + PeopleMedia.Timer.sessionMinutesRemaining > 20 && PeopleMedia.Timer.minutesSinceLastActivity > 16) {
                    PeopleMedia.RefreshSession();
                }
            }
        }
    };
};

PeopleMedia.Popups = new function () {
    this.AjaxErrorMessage = function () {
        return "Whoops... something's amiss. Please try your request again. If you see this error repeatedly, please refresh the page.";
    };
    this.ValidateResponse = function (response) {
        if (response) {
            if (response.redirect) {
                location.href = response.redirect;
                return false;
            }
            if (response.status == "Success") {
                return true;
            }
            else if (response.status != "Success") {
                PeopleMedia.Popups.ShowGenericMessage(response.message);
                return false;
            }
        }
        return false;
    };
    this.ShowGenericMessage = function (message, callback) {
        PeopleMedia.Popups.ClosePopups();
        var html = '<div class="popupshowinfo" >' +
    '<div class="overlaywholescreen"></div>' +
    '<div class="overlayplace">' +
     '   <div class="popupshapestyle genericoverlay ">' +
      '      <div class="largestclosebtn"> <a href="javascript:;" title="Close" class="closebtn"><img src="' + PeopleMedia.SiteImagePath + '/images/imageupload/largestclosebtn.png" border="0"></a> </div>' +
       '     <div class="standardpopupcontent">' +
        '        <h1 id="popupErrorInfoText">Error</h1>' +
         '       <p class="popupupgradebtnspace">' +
         '           <a href="javascript:;"  class="button_style PopupOkButton" title="Ok">Ok</a>' +
         '       </p>' +
         '   </div>' +
        '</div>' +
        '</div>' +
    '</div>';
        $jq('#PopupDisplayAreaDiv').html(html);
            if (message) {
                $jq('#popupErrorInfoText').html(message);
            } else {
                $jq('#popupErrorInfoText').html('There was an unexpected error. Please try again.');
            }
            $jq('.popupshowinfo a').click(function () {
                PeopleMedia.Popups.ClosePopups();
                if (callback)
                    callback();
            });
            $jq('#PopupDisplayAreaDiv').show();
    };
    this.LongMessage = function () {
        var html = '<div class="popupshowblock">' +
    '<div class="overlayplace">' +
    '    <div class="popupshapestyle longmessageoverlay">' +
    '        <div class="largestclosebtn"> <a href="javascript:;" title="Close" class="closebtn"><img src="' + PeopleMedia.SiteImagePath + '/images/imageupload/largestclosebtn.png" border="0" /></a> </div>' +
    '        <div class="longmessagecontent">' +
    '            <h1>Oops...</h1>' +
    '            <p class="longmessagep">You&rsquo;ve reach the maximum allowed length for your message.&nbsp;<br/> ' +
    '            Click Continue to wrap up your message and send.</p>' +
    '            <div class="sharecontentbuttonarea">' +
    '                <p class="longmessagelinksbtn">' +
    '                    <a href="javascript:;" class="button_style" title="Continue">Continue</a>' +
    '                </p>' +
    '            </div>' +
    '        </div>' +
    '    </div>' +
    '</div>' +
    '<div class="overlaywholescreen"></div>' +
'</div>';
        setTimeout('PeopleMedia.Popups.ClosePopups();', 5000);
            $jq('#PopupDisplayAreaDiv').html(html);
            $jq('.popupshowblock a').click(PeopleMedia.Popups.ClosePopups);
            $jq('#PopupDisplayAreaDiv').show();
    };
    this.LearnMore = function (sitepath) {
        var html = '<div class="popupshowblock">' +
    '<div class="overlayplace">' +
    '    <div class="popupshapestyle learnmoreoverlay">' +
    '        <div class="largestclosebtn"> <a href="javascript:;" title="Close" class="closebtn"><img src="' + PeopleMedia.SiteImagePath + '/images/imageupload/largestclosebtn.png" border="0" /></a> </div>' +
    '        <div class="learnmorecontent">' +
    '            <h1>Extended Network and Public Availability of User Profile Information</h1>' +
    '            <p class="learnmorep">Opted-in members can appear on external search results for ' + sitepath + ' as well as on ' + sitepath + ' partner channels for up to two weeks at a time (this can be anywhere on the ' + sitepath + ' website or in any section of our partners\' websites, including the homepage).</p>' + '        </div>' +
    '    </div>' +
    '</div>' +
    '<div class="overlaywholescreen"></div>' +
'</div>';
        $jq('#PopupDisplayAreaDiv').html(html);
        $jq('.popupshowblock a').click(PeopleMedia.Popups.ClosePopups);
        $jq('#PopupDisplayAreaDiv').show();
    };
    this.ShareProfile = function (encodedMemberId, username) {
        var html =
            '<div class="popupshowshare" >' +
            '    <div class="overlaywholescreen"></div>' +
            '    <div class="overlayplace">' +
            '        <div class="popupshapestyle shareoverlay">' +
            '            <div class="largestclosebtn"> <a href="javascript:;" id="ShareProfileCloseButton" title="Close" class="closebtn"><img src="' + PeopleMedia.SiteImagePath + '/images/imageupload/largestclosebtn.png" border="0"></a> </div>' +
            '            <div class="sharecontent">' +
            '                <h1>Do you know someone who might be interested in this member&rsquo;s profile?</h1>' +
            '                <div class="sharecontentemail">' +
            '                    <p>Your friend&rsquo;s email:</p>' +
            '                    <input name="" id="ShareProfileEmailTextbox" type="text">' +
            '                </div>' +
            '                <div class="sharecontenttextarea">' +
            '                    <p>Message to friend (or type your own):</p>' +
            '                    <textarea name="" cols="" rows="" id="ShareProfileTextArea">Hey, I came across this profile on ' + PeopleMedia.Domain + ' and thought you might be interested.</textarea>' +
            '                </div>' +
            '                <div class="sharecontentbuttonarea">' +
            '                    <p class="sharelinksbtn">' +
            '                        <a href="javascript:;" id="ShareProfileCancelButton">Cancel</a>' +
            '                        <a href="javascript:;" id="ShareProfileSendButton" class="button_style" title="Share">Share</a>' +
            '                    </p>' +
            '                </div>' +
            '            </div>' +
            '        </div>' +
            '    </div>' +
            '</div>';
            $jq('#PopupDisplayAreaDiv').html(html);
            $jq('#ShareProfileCloseButton').click(PeopleMedia.Popups.ClosePopups);
            $jq('#ShareProfileCancelButton').click(PeopleMedia.Popups.ClosePopups);
            $jq('#PopupDisplayAreaDiv').show();
        $jq('#ShareProfileSendButton').click(function () {
            PeopleMedia.Popups.ShareProfileComplete(encodedMemberId, username);
            });
    };
    this.ShareProfileComplete = function (encodedMemberId, username) {
        $jq('#ShareProfileSendButton').unbind();
        var email = $jq('#ShareProfileEmailTextbox').val();
        var message = $jq('#ShareProfileTextArea').val();
        var startTime = new Date().getTime();
        var url = '/v3/Ajax/ShareProfile';
        var timeoutValue = 60000;
        $jq.ajax({
            type: "POST",
            url: url,
            data: {
                EncodedMemberId: encodedMemberId,
                Username: username,
                Message: message,
                EmailAddress: email
            },
            dataType: "json",
            success: function (response) {
                if (PeopleMedia.Popups.ValidateResponse(response)) {
                    PeopleMedia.Popups.ClosePopups();
                    PeopleMedia.Popups.ShowGenericMessage(response.message);
                    setTimeout('PeopleMedia.Popups.ClosePopups();', 5000);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                if (errorThrown === 'timeout' || (jqXHR.readyState !== 0 && jqXHR.status !== 0)) {
                    var endTime = new Date().getTime();
                    var duration = (endTime - startTime);
                    // PeopleMedia.Popups.ShowGenericMessage(PeopleMedia.Popups.AjaxErrorMessage());
                    PeopleMedia.Logger.LogAjaxErrorXHR("Ajax request failure", url, { method: "PeopleMedia.Popups.ShareProfileComplete", duration: duration }, jqXHR, textStatus, errorThrown, function () {
                    });
                }
            },
            async: true,
            cache: false,
            timeout: timeoutValue,
            suppressErrors: true
        });
    };
    this.BlockUser = function (encodedMemberId, username, isTodaysMatches) {
        var imagepath = PeopleMedia.SiteImagePath;
        var html = '<div class="popupshowblock" >' +
                   '     <div class="overlaywholescreen"></div>' +
                   '     <div class="overlayplace">' +
                   '         <div class="popupshapestyle blockoverlay">' +
                   '             <div class="largestclosebtn"> <a id="PopupBlockCloseButton" href="javascript:;" title="Close" class="closebtn"><img src="' + imagepath + '/images/imageupload/largestclosebtn.png" border="0"></a> </div>' +
                   '             <div class="blockcontent">' +
                   '                 <h1>Are you sure you want to block <span id="PopupBlockUsernameSpan">this user</span>?</h1>' +
                   '                 <p class="blockcontentp">If you block this user, they will NOT be able to contact you.</p>' +
                   '                 <div class="sharecontentbuttonarea">' +
                   '                     <p class="blocklinksbtn">' +
                   '                         <a href="javascript:;" id="PopupBlockCancelButton">Cancel</a>' +
                   '                         <a href="javascript:;" id="PopupBlockConfirmButton" class="button_style" title="Block User">Block User</a>' +
                   '                     </p>' +
                   '                 </div>' +
                   '             </div>' +
                   '         </div>' +
                   '     </div>' +
                   ' </div>' +
                   ' <div class="popupshowblockconfirm" style="display:none;" >' +
                   '     <div class="overlayplace">' +
                   '         <div class="popupshapestyle blockconfirmoverlay">' +
                   '             <div class="largestclosebtn"> <a href="javascript:;" id="PopupBlockConfirmCloseButton" title="Close" class="closebtn"><img src="' + imagepath + '/images/imageupload/largestclosebtn.png" border="0"></a> </div>' +
                   '             <div class="blockconfirmcontent">' +
                   '                 <h1><span id="PopupBlockConfirmUsernameSpan">This user</span> has been blocked.</h1>' +
                   '             </div>' +
                   '         </div>' +
                   '     </div>' +
                   '     <div class="overlaywholescreen"></div>' +
                   ' </div>';
            $jq('#PopupDisplayAreaDiv').html(html);
            $jq('#PopupBlockUsernameSpan').html(username);
            $jq('#PopupBlockConfirmUsernameSpan').html(username);
            $jq('#PopupBlockConfirmButton').click(function () {
                PeopleMedia.Popups.ConfirmBlock(encodedMemberId, username, isTodaysMatches);
                });
            $jq('#PopupBlockCloseButton').click(PeopleMedia.Popups.ClosePopups);
            $jq('#PopupBlockCancelButton').click(PeopleMedia.Popups.ClosePopups);
            $jq('#PopupDisplayAreaDiv').show();
    };
    this.ConfirmBlock = function (encodedMemberId, username, isTodaysMatches) {
        $jq('#PopupBlockConfirmButton').unbind();
        $jq('#PopupBlockConfirmCloseButton').click(PeopleMedia.Popups.ClosePopups);
        $jq('.popupshowblock').hide();
        $jq('.popupshowblockconfirm').show();
        var startTime = new Date().getTime();
        var url = '/v3/Ajax/BlockUser';
        var timeoutValue = 60000;
        $jq.ajax({
            type: "POST",
            url: url,
            data: {
                EncodedMemberId: encodedMemberId,
                BlockUser: true,
                QueryString: window.location.search,
                Username: username
            },
            dataType: "json",
            success: function (response) {
                if (PeopleMedia.Popups.ValidateResponse(response)) {
                    var todaysMatches = isTodaysMatches == 'True';
                    if (!todaysMatches) {
                        if (response.backTo) {
                            if (response.backTo == ":back") {
                                setTimeout('history.back();', 5000);
                            } else {
                                setTimeout('location.href = \'' + response.backTo + '\';', 5000);
                            }
                        }
                    } else {
                        setTimeout('location.reload();', 2000);
                    }
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                if (errorThrown === 'timeout' || (jqXHR.readyState !== 0 && jqXHR.status !== 0)) {
                    var endTime = new Date().getTime();
                    var duration = (endTime - startTime);
                    // PeopleMedia.Popups.ShowGenericMessage(PeopleMedia.Popups.AjaxErrorMessage());
                    PeopleMedia.Logger.LogAjaxErrorXHR("Ajax request failure", url, { method: "PeopleMedia.Popups.ConfirmBlock", duration: duration }, jqXHR, textStatus, errorThrown, function () {
                    });
                }
            },
            async: true,
            cache: false,
            timeout: timeoutValue,
            suppressErrors: true
        });
    };
    this.Init = function () {
    };
    this.ConfirmReportConcernPopup = function (response) {
        PeopleMedia.Popups.ClosePopups();
        var html = '<div class="popupshowinfo" >' +
            '<div class="overlaywholescreen"></div>' +
            '<div class="overlayplace confirmreportconcernoverlay">' +
             '   <div class="popupshapestyle confirmreportconcernoverlay">' +
              '      <div class="largestclosebtn"> <a href="javascript:;" title="Close" class="closebtn"><img src="' + PeopleMedia.SiteImagePath + '/images/imageupload/largestclosebtn.png" border="0"></a> </div>' +
               '     <div class="standardpopupcontent">' +
                '        <h1 id="popupErrorInfoText">Error</h1>' +
                ' <div class="reportconcerncontentbuttonarea">' +
                '     <p class="reportconcernbtn">' +
                '         <a href="javascript:;" id="PopupReportConcernConfirmButton" class="button_style" title="Ok">Ok</a>' +
                '     </p>' +
                ' </div>' +
                 '   </div>' +
                '</div>' +
                '</div>' +
            '</div>';
        $jq('#PopupDisplayAreaDiv').html(html);
        if (response) {
            if (response.message) {
                $jq('#popupErrorInfoText').html(response.message);
                if (response.concernId && (response.concernId == 2 || response.concernId == 5)) {
                    //Don't show comment box for fake profile or scammer
                    $jq('.lightgrayreportconcern').hide();
                }
            }
            else {
                $jq('#popupErrorInfoText').html('There was an unexpected error. Please try again.');
            }
            if (response.rightNowUrl) {
                $jq('#rnIframedContent').attr('src', response.rightNowUrl);
                if (response.isMobileUser) {
                    $jq('#rnIframedContent').attr('width', '250');
                    $jq('#rnIframedContent').attr('height', '500');
                }
            }
        }
        $jq('.popupshowinfo a.closebtn').click(function () {
            PeopleMedia.Popups.ClosePopups();
        });
        $jq('#PopupReportConcernConfirmButton').click(function () {
            PeopleMedia.Popups.ClosePopups();
        });
        $jq('#PopupDisplayAreaDiv').show();
    };

    this.ShowReportConcernComment = function (encodedMemberId, concernType, isTodaysMatches, defaultText) {
        PeopleMedia.Popups.ClosePopups();

        var html =
            '<div class="popupshowshare" >' +
            '    <div class="overlaywholescreen"></div>' +
            '    <div class="overlayplace raccommentoverlay">' +
            '        <div class="popupshapestyle raccommentoverlay">' +
            '            <div class="largestclosebtn"> <a href="javascript:;" id="ReportConcernCloseButton" title="Close" class="closebtn"><img src="' + PeopleMedia.SiteImagePath + '/images/imageupload/largestclosebtn.png" border="0"></a> </div>' +
            '            <div class="sharecontent raccommentcontent">' +
            '                <h1>Report A Concern</h1>' +
            //'                <div class="sharecontentemail">' +
            //'                    <p>Your username: meso</p>' +
            //'                    <p>Your email: meso@testxp.com</p>' +
            //'                </div>' +
            '                <div class="sharecontenttextarea">' +
            '                    <p>Comments:</p>' +
            '                    <textarea name="" cols="" rows="" id="ReportConcernTextArea">Type your comments here.</textarea>' +
            '                    <p class="remainingcharacters">Characters Remaining: <span>255</span></p>' +
            '                </div>' +
            '                <div class="sharecontentbuttonarea">' +
            '                    <p class="sharelinksbtn">' +
            '                        <a href="javascript:;" id="ReportConcernCancelButton">Cancel</a>' +
            '                        <a href="javascript:;" id="ReportConcernSubmitButton" class="button_style" title="Submit Concern">Submit Concern</a>' +
            '                    </p>' +
            '                </div>' +
            '            </div>' +
            '        </div>' +
            '    </div>' +
            '</div>';
        $jq('#PopupDisplayAreaDiv').html(html);
        $jq('#ReportConcernCloseButton').click(PeopleMedia.Popups.ClosePopups);
        $jq('#ReportConcernCancelButton').click(PeopleMedia.Popups.ClosePopups);
        $jq('#PopupDisplayAreaDiv').show();
        $jq('#ReportConcernTextArea').val(defaultText);
        $jq('#ReportConcernSubmitButton').click(function () {
            var commentText = $jq('#ReportConcernTextArea').val();
            PeopleMedia.Popups.SubmitReportConcernComment(encodedMemberId, commentText, concernType, isTodaysMatches);
        });
        var commentLength = $jq('#ReportConcernTextArea').val().length;
        $jq('#ReportConcernTextArea').parent().find('.remainingcharacters span').html(255 - commentLength);

        $jq("#ReportConcernTextArea").keyup(function () {
            var limit = 255;
            var text = $jq(this).val();
            var chars = text.length;
            if (chars > limit) {
                var new_text = text.substr(0, limit);
                $jq(this).val(new_text);
            }
            var remain = limit - chars;
            if (remain < 0) {
                remain = 0;
            }

            $jq(this).parent().find('.remainingcharacters span').html(remain);
        });

        if (isTodaysMatches && isBlocked) {
            $jq('#ReportConcernCloseButton').click(function () {
                PeopleMedia.Popups.ClosePopups();
                setTimeout('location.reload();', 100);
            });
        }
    };

    this.SubmitReportConcern = function (encodedMemberId, username, objectId, callback, isTodaysMatches, url, showRACComment) {
        var concernType = $jq('#ReportConcernTypeSelect').val();
        var message = $jq('#ReportConcernTextArea').val();
        var isBlocked = $jq('#ReportConcernBlockUserCheckbox').prop('checked');

        var confirmBlock = true;
        if (isBlocked) {
            confirmBlock = confirm('Are you sure you want to block this user?');
        }
        if (confirmBlock) {
            $jq('#PopupReportConcernConfirmButton').unbind();

            var startTime = new Date().getTime();
            var url = '/v3/Ajax/ReportConcern';
            var timeoutValue = 60000;
            $jq.ajax({
                type: "POST",
                url: url,
                data: {
                    EncodedMemberId: encodedMemberId,
                    Message: message,
                    BlockUser: isBlocked,
                    ConcernId: concernType,
                    Username: username,
                    QueryString: window.location.search,
                    ObjectId: objectId,
                    UnknownUrl: url
                },
                dataType: "json",
                success: function (response) {
                    if (PeopleMedia.Popups.ValidateResponse(response)) {
                        if (callback) {
                            callback();
                        }
                        var todaysMatches = isTodaysMatches == 'True';
                        var racComment = showRACComment == 'True';
                        if (!todaysMatches && !racComment) {
                            PeopleMedia.Popups.ClosePopups();
                            PeopleMedia.Popups.ConfirmReportConcernPopup(response, url);
                        } else if (todaysMatches && !racComment) {
                            PeopleMedia.Popups.ClosePopups();
                            PeopleMedia.Popups.ConfirmReportConcernPopup(response, url);
                            setTimeout('location.reload();', 500);
                        } else {
                            PeopleMedia.Popups.ShowReportConcernComment(encodedMemberId, concernType, todaysMatches, response.defaultText);
                        }
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (errorThrown === 'timeout' || (jqXHR.readyState !== 0 && jqXHR.status !== 0)) {
                        var endTime = new Date().getTime();
                        var duration = (endTime - startTime);
                        // PeopleMedia.Popups.ShowGenericMessage(PeopleMedia.Popups.AjaxErrorMessage());
                        PeopleMedia.Logger.LogAjaxErrorXHR("Ajax request failure", url, { method: "PeopleMedia.Popups.SubmitReportConcern", duration: duration }, jqXHR, textStatus, errorThrown, function () {
                        });
                    }
                },
                async: true,
                cache: false,
                timeout: timeoutValue,
                suppressErrors: true
            });
        }
    };
    this.SubmitReportConcernComment = function (encodedMemberId, commentText, concernType, isTodaysMatches) {
        var message = $jq('#ReportConcernTextArea').val();

        var startTime = new Date().getTime();
        var url = '/v3/Ajax/ReportConcernComment';
        var timeoutValue = 60000;
        $jq.ajax({
            type: "POST",
            url: url,
            data: {
                EncodedMemberId: encodedMemberId,
                Message: commentText,
                ConcernId: concernType
            },
            dataType: "json",
            success: function (response) {
                if (PeopleMedia.Popups.ValidateResponse(response)) {
                    var todaysMatches = isTodaysMatches == 'True';
                    $jq('.popupshapestyle').removeClass('raccommentoverlay');
                    $jq('.popupshapestyle').addClass('racclose');
                    $jq('.raccommentcontent').html('<div style="text-align: center;"><h1>Thank you, your concern is taken very seriously and may require a few days to fully investigate.' +
                            '</h1></br><p class="reportconcernbtn">' +
                       '         <a href="javascript:;" id="ReportConcernOkButton" class="button_style" title="Ok">Ok</a>' +
                       '     </p></div>');
                    $jq('#ReportConcernOkButton').click(function () {
                        PeopleMedia.Popups.ClosePopups();
                    });
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                if (errorThrown === 'timeout' || (jqXHR.readyState !== 0 && jqXHR.status !== 0)) {
                    var endTime = new Date().getTime();
                    var duration = (endTime - startTime);
                    // PeopleMedia.Popups.ShowGenericMessage(PeopleMedia.Popups.AjaxErrorMessage());
                    PeopleMedia.Logger.LogAjaxErrorXHR("Ajax request failure", url, { method: "PeopleMedia.Popups.SubmitReportConcernComment", duration: duration }, jqXHR, textStatus, errorThrown, function () {
                    });
                }
            },
            async: true,
            cache: false,
            timeout: timeoutValue,
            suppressErrors: true
        });
    };
    this.ReportConcern = function (encodedMemberId, username, objectId, concernType, url, isTodaysMatches) {
        var html = '<div class="popupshowreportconcern" >' +
                    '<div class="overlaywholescreen"></div>' +
                    '<div class="overlayplace reportconcernoverlay">' +
                    '    <div class="popupshapestyle reportconcernoverlay">' +
                    '        <div class="largestclosebtn"> <a href="javascript:;" id="ReportConcernCloseButton" title="Close" class="closebtn"><img src="' + PeopleMedia.SiteImagePath + '/images/imageupload/largestclosebtn.png" border="0"></a> </div>' +
                    '        <div class="reportconcerncontent">' +
                    '            <h1>Please let us know if this member has behaved inappropriately, or has violated the terms and conditions of the site in any way. We want to make sure your experience' +
                    '    on ' + PeopleMedia.Domain + ' is the best it can be.</h1>' +
                    '<div class="reportconcerncontentmiddle">' +
                        '<div class="reportconcerncontentmiddleleft">' +
                        '    <p>What is your concern?</p>' +
                        '</div>' +
                        '<div class="reportconcerncontentmiddlecenter">' +
                        '    <select id="ReportConcernTypeSelect">' +
                        '        <option value="1">Inappropriate Text</option>' +
                        '        <option value="2">Fake Profile</option>' +
                        '        <option value="5">Scammer</option>' +
                        '        <option value="3">Inappropriate Photo</option>' +
                        '        <option value="7">Inappropriate Behavior</option>' +
                        '        <option value="4">Other</option>' +
                        '    </select>' +
                   '     </div>' +
                   '     <div class="reportconcerncontentmiddleright">' +
                   '         <input id="ReportConcernBlockUserCheckbox" name="" type="checkbox" value="" checked><p><label for="ReportConcernBlockUserCheckbox">Block this user</label></p>' +
                   '     </div>' +
                   ' </div>' +
                   ' <div class="reportconcerncontentbuttonarea">' +
                   '<div class="RightNowContainerInternal" style="display:none;">' +
                   '<iframe id="rnIframedContent" name="rnIframedContent" src="" width="794" height="400" scrolling="no" frameborder="0">' +
                   '</iframe>' +
                   '</div>' +
                   '     <div><p class="lightgrayreportconcern reportconcernpmargin" style="width: 100%;">Your report and identity will NOT be shared with this member.</br></p>' +
                   '     <p class="lightgrayreportconcern reportconcerncommenttext reportconcernpmargin">To provide additional details regarding </br> your concern <a href="javascript:;" id="reportconcerncomment">click here</a></p></div>' +
                   '     <p class="reportconcernbtn">' +
                   '         <a href="javascript:;" id="PopupReportConcernConfirmButton" class="button_style" title="Report Member">Report Member</a>' +
                   '     </p>' +
                   ' </div>' +
                   '</div></div></div></div>';
            $jq('#PopupDisplayAreaDiv').html(html);
            $jq('#PopupDisplayAreaDiv').show();
            $jq('#ReportConcernCloseButton').click(PeopleMedia.Popups.ClosePopups);
        $jq('#ReportConcernTextArea').keyup(function () {
                var limit = 255;
                var text = $jq(this).val();  
                var chars = text.length;  
            if (chars > limit) {
                    var new_text = text.substr(0, limit);  
                    $jq(this).val(new_text);  
                }  
            var remain = limit - chars;
                if (remain < 0) {
                    remain = 0;
                }

                $jq('#ReportConcernTextAreaCharactersLeftSpan').html(remain);
                });
            $jq('#ReportConcernTypeSelect option[value=\'6\']').remove();

            $jq('#ReportConcernTypeSelect').change(function () {
                var selected = $jq('#ReportConcernTypeSelect').val();
                if (selected == 2 || selected == 5) {
                    $jq('.reportconcerncommenttext').hide();
                }
                else {
                    $jq('.reportconcerncommenttext').show();
                }
            });

            var isUrl = false;
        if (concernType && concernType == 'image') {
            $jq('#ReportConcernTypeSelect')[0].selectedIndex = 3;
            }
        else if (concernType && concernType == 'link') {
                isUrl = true;
                $jq('#ReportConcernCloseButton').click(function () {
                    $jq('#ReportConcernTypeSelect option').remove();
                    $jq('#ReportConcernTypeSelect').append($select.find('option'));
                    $jq('#ReportConcernCloseButton').unbind('click').click(PeopleMedia.Popups.ClosePopups);
                });
                var $select = $jq('#ReportConcernTypeSelect').clone();
                $jq('#ReportConcernTypeSelect option').remove();
                $jq('#ReportConcernTypeSelect').append('<option value=\'6\' selected>unknown url</option>');
            $jq('#ReportConcernTypeSelect')[0].selectedIndex = 0;
                $jq('#ReportConcernBlockUserCheckbox').removeAttr('checked');
                if (url) {
                    $jq('#ReportConcernTextArea').val('User tried to send me to ' + url);
                }
            }
            else {
                if (objectId) {
                $jq('#ReportConcernTypeSelect')[0].selectedIndex = 3;
                } else {
                $jq('#ReportConcernTypeSelect')[0].selectedIndex = 0;
                }
            }
        $jq('#PopupReportConcernConfirmButton').click(function () {
                PeopleMedia.Popups.SubmitReportConcern(encodedMemberId, username, objectId, null, isTodaysMatches, url);
            });
            $jq('#reportconcerncomment').click(function () {
                PeopleMedia.Popups.SubmitReportConcern(encodedMemberId, username, objectId, null, isTodaysMatches, url, 'True');
            });
    };
    this.FlirtSent = function (encodedMemberId, username, gender, hasPhoto, fromPage, featureName, upn, isBdayFlirt) {
        var quickTip = "";
        var quickTipNumber = 0;
        var genderObjective = (gender === 1) ? "Him" : "Her";
        var defaultTitle = "<h1>Flirt Sent!</h1>";
        var defaultText = "Hello, you caught my attention with...";

        var tipsMaleProfile = [
            'Quick Tip: Just say "hi" and introduce yourself. Yes. It really <i>is</i> that simple to stand out.',
            'Did you know the guys on the site prefer messages to flirts? Yes! And they are 5x times more likely to respond to your message than your flirt.',
            'Quick Tip: Stand out from the flirts and tell him one thing that you liked about his profile.',
            'Quick Tip: Make him feel like a million bucks by mentioning what you like about his profile.',
            'Quick Tip: Increase your odds of getting a reply - ask about his interests.'
        ];
        var tipsFemaleProfile = [
            'Quick Tip: Just say "hi" and introduce yourself. Yes. It really <i>is</i> that simple to stand out.',
            'Did you know...<br/>Women greatly prefer getting a personalized message over a flirt. So send a quick note to increase your chance of a reply by 5X!',
            'Quick Tip: Tell her one thing that you liked about her profile.',
            'Quick Tip: Increase your odds of getting a reply - ask about her interests.',
            'Quick Tip: Don\'t be shy, say Hi and let her know you\'re interested.'
        ];

        var buttonCTA = 'Tell ' + genderObjective;
        
        if (isBdayFlirt != null && isBdayFlirt == true) {
            defaultTitle = "<h1>Birthday Wish Sent</h1>"; 
            defaultText = "Happy Birthday! I hope you..."; 
            quickTip = "Personalize Your Birthday Wish with a Message!";
            buttonCTA = "Send Message"; 
        } else if (hasPhoto) {
            quickTip = 'Quick Tip: Compliment ' + genderObjective.toLowerCase() + ' on your favorite photo. What stands out to you?';
        } else {
            quickTipNumber = Math.floor(Math.random() * tipsMaleProfile.length);
            quickTip = (gender === 1) ? tipsMaleProfile[quickTipNumber] : tipsFemaleProfile[quickTipNumber];
        }
        var html = '<div class="popupshowflirtsent" >' +
                   '   <div class="overlayplace">' +
                   '       <div class="popupshapestyle flirtsentoverlay2">' +
                   '           <div class="largestclosebtn"> <a id="PopupSendMessageCloseButton" href="javascript:;" title="Close" class="closebtn"><img src="' + PeopleMedia.SiteImagePath + '/images/imageupload/largestclosebtn.png" border="0"></a> </div>' +
                   '           <div class="flirtsentcontent">' + defaultTitle + 
                   '               <div class="flirtsentcontenttextarea">' +
                   '                   <p>' + quickTip + '</p>' +
                   '                   <textarea id="PopupSendMessageTextArea" name="PopupSendMessageTextArea" cols="20" rows="2">' + defaultText + '</textarea>' +
                   '               </div>' +
                   '               <div class="flirtsentcontentbuttonarea">' +
                   '                   <p class="flirtsentlinksbtn">' +
                   '                       <a href="javascript:;" id="PopupSendMessageCancelButton">Cancel</a>' +
                   '                       <a href="javascript:;" id="PopupSendMessageConfirmButton" class="button_style" title="Tell ' + genderObjective + '">' + buttonCTA + '</a>' +
                   '                   </p>' +
                   '               </div>' +
                   '           </div>' +
                   '           <p class="clearfixfix">&nbsp;</p>' +
                   '       </div>' +
                   '   </div>' +
                   '   <div class="overlaywholescreen"></div>' +
                   '</div>';
        $jq('#PopupDisplayAreaDiv').html(html);
        $jq('#PopupSendMessageConfirmButton').click(function () {
            PeopleMedia.Popups.ConfirmSendMessage(encodedMemberId, username, gender, hasPhoto, fromPage, featureName, upn, isBdayFlirt);
        });
        $jq('#PopupSendMessageCloseButton').click(PeopleMedia.Popups.ClosePopups);
        $jq('#PopupSendMessageCancelButton').click(PeopleMedia.Popups.ClosePopups);
        $jq('#PopupSendMessageTextArea').focus(function () {
            if ($jq(this).val() === defaultText) {
                var defaultText2 = defaultText.substring(0, defaultText.length - 3) + ' ';
                PeopleMedia.Popups.setCursorPosition("PopupSendMessageTextArea", defaultText2.length);
                $jq(this).val(defaultText2);
                // Work around Chrome problem not allowing cursor position change from focus event
                window.setTimeout('PeopleMedia.Popups.setCursorPosition("PopupSendMessageTextArea", ' + defaultText2.length.toString() + ');', 500);
            }
        });
        $jq("#PopupSendMessageTextArea").keyup(function () {
            var limit = 3000;
            var text = $jq(this).val();
            var chars = text.length;
            if (chars > limit) {
                var new_text = text.substr(0, limit);
                $jq(this).val(new_text);
            }
        });
        $jq('#PopupDisplayAreaDiv').show();
    };
    this.ConfirmSendMessage = function (encodedMemberId, username, gender, hasPhoto, fromPage, featureName, upn, isBdayFlirt) {
        $jq('#PopupSendMessageConfirmButton').unbind();
        $jq('#PopupSendMessageCancelButton').click(PeopleMedia.Popups.ClosePopups);
        $jq('.popupshowflirtsent').hide();
        var message = $jq('#PopupSendMessageTextArea').val().replace(/^\s+|\s+$/g, "");
        if (message && message !== '' && message !== 'Hello, you caught my attention with...' && message !== 'Hello, you caught my attention with' && message !== 'Happy Birthday! I hope you...' && message !== 'Happy Birthday! I hope you') {
            var startTime = new Date().getTime();
            var url = '/v3/Ajax/SendMessage';
            var timeoutValue = 60000;
            $jq.ajax({
                type: "POST",
                url: url,
                data: {
                    EncodedMemberId: encodedMemberId,
                    Message: message,
                    UPN: upn,
                    FromPage: fromPage,
                    FeatureName: featureName
                },
                dataType: "json",
                success: function (response) {
                    if (response) {
                        if (response.redirect) {
                            location.href = response.redirect;
                            return false;
                        } else if (response.status != "Success") {
                            PeopleMedia.Popups.ShowGenericMessage(response.message, function () {
                                PeopleMedia.Popups.FlirtSent(encodedMemberId, username, gender, hasPhoto, fromPage, featureName, upn, isBdayFlirt);
                            });
                            return false;
                        }
                    }
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    if (errorThrown === 'timeout' || (jqXHR.readyState !== 0 && jqXHR.status !== 0)) {
                        var endTime = new Date().getTime();
                        var duration = (endTime - startTime);
                        // PeopleMedia.Popups.ShowGenericMessage(PeopleMedia.Popups.AjaxErrorMessage());
                        PeopleMedia.Logger.LogAjaxErrorXHR("Ajax request failure", url, { method: "PeopleMedia.Popups.ConfirmSendMessage", duration: duration }, jqXHR, textStatus, errorThrown, function () {
                        });
                    }
                },
                async: true,
                cache: false,
                timeout: timeoutValue,
                suppressErrors: true
            });
        } else {
            PeopleMedia.Popups.ShowGenericMessage("Please enter a message!", function () {
                PeopleMedia.Popups.FlirtSent(encodedMemberId, username, gender, hasPhoto, fromPage, featureName, upn, isBdayFlirt);
            });
            return false;
        }
    };
    this.setCursorPosition = function (inputId, pos) {
        var input = document.getElementById(inputId);
        if (input && input.value) {
            PeopleMedia.Popups.setSelectionRange(input, pos, pos);
        }
    };
    this.setSelectionRange = function (input, selectionStart, selectionEnd) {
        if (input.setSelectionRange) {
            input.focus();
            input.setSelectionRange(selectionStart, selectionEnd);
        } else if (input.createTextRange) {
            var range = input.createTextRange();
            range.collapse(true);
            range.moveEnd('character', selectionEnd);
            range.moveStart('character', selectionStart);
            range.select();
        }
    };
    this.ClosePopups = function () {
        $jq('#PopupDisplayAreaDiv').hide();
    };
    this.ShowScamTips = function () {
        var imagepath = PeopleMedia.SiteImagePath;
        var html = '<div class="overlayplace" id="ScamTipsPopup" >' +
                    '<div class="overlaywholescreen"> </div>' +
                    '<div class="scamsoverlay popupshapestyle">' +
                    '    <div class="largestclosebtn"> <a href="javascript:;" title="Close" class="closebtn"><img src="' + imagepath + '/images/imageupload/largestclosebtn.png" border="0"></a> </div>' +
                    '    <div class="scamspopupcontent">' +
                    '        <div class="scamspopupcontenttop">' +
                    '            <h1>Stay safe online and avoid scammers!</h1>' +
                    '            <p>To stay safe online, keep an eye out for these "red flags" that someone who has contacted' +
                    '                you may not be who they say they are.</p>' +
                    '        </div>' +
                    '        <div class="scamspopupcontentmiddle">' +
                    '            <h2>Scammers will: </h2>' +
                    '            <div class="scamspopupcontentmiddleleft">' +
                    '                <div class="scamspopupcontentmiddlerepeat">' +
                    '                    <img src="' + imagepath + '/images/popup/bluecheckmark.gif">' +
                    '                    <p>Ask you to talk or chat using an outside messaging service or email account</p>' +
                    '                </div>' +
                    '                <div class="scamspopupcontentmiddlerepeat">' +
                    '                    <img src="' + imagepath + '/images/popup/bluecheckmark.gif">' +
                    '                    <p>Vanish mysteriously from the site, often after being caught and removed</p>' +
                    '               </div>' +
                    '               <div class="scamspopupcontentmiddlerepeat">' +
                    '                   <img src="' + imagepath + '/images/popup/bluecheckmark.gif">' +
                    '                    <p>Talk about "destiny" or "fate" when meeting you</p>' +
                    '                </div>' +
                    '                <div class="scamspopupcontentmiddlerepeat">' +
                    '                    <img src="' + imagepath + '/images/popup/bluecheckmark.gif">' +
                    '                    <p>Claim to be recently widowed</p>' +
                    '                </div>' +
                    '            </div>' +
                    '            <div class="scamspopupcontentmiddleright">' +
                    '        <div class="scamspopupcontentmiddlerepeat">' +
                    '                    <img src="' + imagepath + '/images/popup/bluecheckmark.gif">' +
                    '                    <p>Ask for your address or contact info under the guise of sending flowers or gifts</p>' +
                    '                </div>' +
                    '                <div class="scamspopupcontentmiddlerepeat">' +
                    '                    <img src="' + imagepath + '/images/popup/bluecheckmark.gif">' +
                    '                    <p>Make a lot of grammatical and spelling errors</p>' +
                    '                </div>' +
                    '                <div class="scamspopupcontentmiddlerepeat">' +
                    '                    <img src="' + imagepath + '/images/popup/bluecheckmark.gif">' +
                    '                    <p>Say they live in the U.S. but are currently traveling abroad</p>' +
                    '               </div>' +
                    '                <div class="scamspopupcontentmiddlerepeat">' +
                    '                    <img src="' + imagepath + '/images/popup/bluecheckmark.gif">' +
                    '                    <p>Always eventually ask you for money</p>' +
                    '                </div>' +
                    '            </div>' +
                    '            <p class="clearfix">&nbsp;</p>' +
                    '        </div>' +
                    '        <div class="scamspopupcontentbottom">' +
                    '            <p>If you suspect that someone is a scammer or is exhibiting strange behavior of any kind, click on the "Report a Concern" button from their profile to notify us immediately.</p>' +
                    '            <p>By helping us combat online scams you enrich the experience for countless real people looking for love on ' + PeopleMedia.Domain + '.</p>' +
                    '        </div>' +
                    '    </div>' +
                    '</div>' +
                    '</div>';
            $jq('#PopupDisplayAreaDiv').html(html);
            $jq('#PopupDisplayAreaDiv').show();
            $jq('#ScamTipsPopup .closebtn').click(PeopleMedia.Popups.ClosePopups);
    };
    this.ShowExternalLink = function (encodedMemberId, username, messageId, url) {
        var domainLower = PeopleMedia.BaseDomain.toLowerCase();
        var html = '<div class="overlayplace" id="ExternalLinkPopup" >' +
                   '     <div class="overlaywholescreen"> </div>' +
                   '     <div class="securtytipoverlay popupshapestyle" >' +
                   '         <div class="largestclosebtn"> <a href="javascript:;" title="Close" class="closebtn"><img src="' + PeopleMedia.SiteImagePath + '/images/imageupload/largestclosebtn.png" border="0" /></a> </div>' +
                   '         <div class="securtiytippopupcontent">' +
                   '             <div class="securtiytippopupcontenttop">' +
                   '                 <h1>Security Tip</h1>' +
                   '             </div>' +
                   '             <div class="securtiytippopupcontentmiddle">' +
                   '                 <h1>Heads up!</h1>' +
                   '                 <p>The link you just clicked leads to a page that is not hosted by us. We want to remind you not to enter your username and password into this or any page that&rsquo;s not hosted by us. </p>' +
                   '                 <h1>Why does it matter?</h1>' +
                   '                 <p>This is a tactic used in Phishing scams to get your username and password. </p>' +
                   '                 <h1>How can you tell?</h1>' +
                   '                 <p>Links hosted by us should look like: ' + domainLower + '. It&rsquo;s ok if there are letters or numbers after the &ldquo;.com,&rdquo; but if there is anything between the &ldquo;' + domainLower + '&rdquo; and the &ldquo;.com&rdquo; then it&rsquo;s not us. </p>' +
                   '                 <p class="clearfix">&nbsp;</p>' +
                   '             </div>' +
                   '             <div class="securtiytippopupcontentbottom">' +
                   '                 <div class="securtiytippopupcontentbottomleft">' +
                   '                     <p>Want to report this link to us? <a href="javascript:;" id="ExternalLinkReportConcernButton">Click here</a></p>' +
                   '                 </div>' +
                   '                 <div class="securtiytippopupcontentbottomright">' +
                   '                     <p><a href="javascript:;" class="button_style" title="Cancel" id="ExternalLinkCancelButton">Cancel</a></p>' +
                   '                     <p><a href="javascript:;" id="ExternalLinkConfirmButton" target="_blank">View Link</a></p>' +
                   '                 </div>' +
                   '                 <p class="clearfix">&nbsp;</p>' +
                   '             </div>' +
                   '         </div>' +
                   '     </div>' +
                   ' </div>';

            $jq('#PopupDisplayAreaDiv').html(html);
            $jq('#PopupDisplayAreaDiv').show();
            $jq('#ExternalLinkPopup a').click(PeopleMedia.Popups.ClosePopups);
        $jq('#ExternalLinkConfirmButton').attr('href', 'http://' + url);
            $jq('#ExternalLinkReportConcernButton').unbind().click(function () {
                PeopleMedia.Popups.ClosePopups();
            PeopleMedia.Popups.ReportConcern(encodedMemberId, username, messageId, 'link', url);
            });
    };
};




(function ($jq) {
    if($jq.widget != null){
        $jq.widget("ui.combobox", {
            _create: function () {
                var self = this,
                    select = this.element.hide(),
                    selected = select.children(":selected"),
                    value = selected.val() ? selected.text() : "";
                var input = this.input = $jq("<input name='DisplayText'>")
                    .insertAfter(select).addClass("inputtext")
                    .val(value)
                    .autocomplete({
                        delay: 0,
                        minLength: 1,
                        selectFirst: true,
                        source: function (request, response) {
                            var matcher = new RegExp($jq.ui.autocomplete.escapeRegex(request.term), "i");
                            response(select.children("option").map(function () {
                                var text = $jq(this).text();
                                if (this.value && (!request.term || matcher.test(text)))
                                    return {
                                        label: text.replace(
                                            new RegExp(
                                                "(?![^&;]+;)(?!<[^<>]*)(" +
                                                    $jq.ui.autocomplete.escapeRegex(request.term) +
                                                    ")(?![^<>]*>)(?![^&;]+;)", "gi"
                                            ), "<strong>$1</strong>"),
                                        value: text,
                                        option: this
                                    };
                            }));
                        },
                        select: function (event, ui) {
                            ui.item.option.selected = true;
                            self._trigger("selected", event, {
                                item: ui.item.option
                            });
                            select.trigger('change');
                        }
                    })
                    .blur(function(){
                            var textbox = $jq(this);
                                var matcher = new RegExp($jq.ui.autocomplete.escapeRegex(textbox.val()), "i"),
                                    valid = false;
                                if(textbox.val() != ''){
                                    select.children("option").each(function () {
                                        var option = $jq(this);
                                        if (matcher.test(option.text())) {
                                            textbox.val(option.text());
                                            //$jq(this).text().match(matcher)) {
                                            this.selected = valid = true;
                                            select.trigger('change');
                                            return false;
                                        }
                                    });
                                }
                                if (!valid) {
                                    // remove invalid value, as it didn't match anything
                                    select.children("option").each(function () {
                                        var option = $jq(this);
                                        if(select.val() == option.val()){
                                            textbox.val(option.text());
                                            return false;
                                        }
                                    });
                                    return false;
                                }
                            })
                    .focus(function(){
                        $jq(this).val('');
                    })
                    .addClass("ui-widget ui-widget-content ui-corner-left ui-corner-right");


                input.data("autocomplete")._renderItem = function (ul, item) {
                    return $jq("<li></li>")
                        .data("item.autocomplete", item)
                        .append("<a>" + item.label + "</a>")
                        .appendTo(ul);
                };

            },

            destroy: function () {
                this.input.remove();
                this.button.remove();
                this.element.show();
                $jq.Widget.prototype.destroy.call(this);
            }
        });    
    }
    
})(jQuery);
PeopleMedia.ChatPane = (function ($) {
    var chatPane = null;
    var columnLeft = null;
    var pub = [];
    var wired = false;
    var win = null;
    pub.IsEnabled = false;
    var isShowing = false;
    var lastToggle = null;
    var shouldToggle = function() {
        if (lastToggle == null) {
            lastToggle = new Date();
            return true;
        } else {
            var newToggle = new Date();
            if ((newToggle - lastToggle) > 600) {
                lastToggle = newToggle;
                return true;
            }
        }
        return false;
    };
    pub.ShowChat = function (forceEnabled) {
        if (forceEnabled == true || forceEnabled == false) {
            pub.IsEnabled = forceEnabled;
        }
        if (wired == false) {
            win = $(window);
            chatPane = $('div.chatPane');
            columnLeft = $('div#columnleft');
           
            wired = true;
        }
        if (chatPane == null || chatPane.length == 0 || pub.IsEnabled == false || !shouldToggle()) {
            return;
        }
        isShowing = true;
        win.off('scroll').on('scroll', scrolled);
        win.off('resize').on('resize', resized);
        chatPane.animate({ 'right': '0px' }, 400);
        resized();

        $.ajax({
            url: '/v3/chat/getavailablemembers',
            type: 'GET',
            success: populateMembers,
            error: function() {
                var h1 = chatPane.find('>h1').clone();
                chatPane.children().remove();
                chatPane.append(h1);
                var h2 = $('<h2>Sorry, we are unable to load chat list at this time...</h2>');
                chatPane.append(h2);
            }
        });
    };
    pub.ToggleChat = function() {
        if (isShowing == true) {
            pub.HideChat();
        } else {
            pub.ShowChat();
        }
    };
    var populateMembers = function(result) {
        var h1 = chatPane.find('>h1').clone();
        chatPane.children().remove();
        chatPane.append(h1);
        if (result.success == true) {
            if (result.Members && result.Members.length > 0) {
                $.each(result.Members, function(fx) {
                    var member = result.Members[fx];
                    var div = $('<div />');
                    var img = $('<img />');
                    img.prop('src', member.PhotoUrl);
                    div.append(img);
                    div.prop('title', 'Click to Chat with ' + member.Username + ' Now!');
                    div.append('<h3>' + member.Username + '</h3>');
                    if (member.IsFavorite == true) {
                        div.addClass('fav');
                        if (member.Gender == 1) {
                            div.append('<h4>He\'s a Favorite!</h4>');
                        } else {
                            div.append('<h4>She\'s a Favorite!');
                        }
                    } else {
                        div.append('<h4>' + member.Age + ' | ' + member.Location + '</h4>');

                    }
                    if (result.IsPaid) {
                        div.on('click', function() { initiateChat(member); });
                    } else {
                        div.on('click', function() {
                            location.href = result.UpgradeUrl + '&profile=' + member.EncryptedMemberId;
                        });
                    }
                    chatPane.append(div);
                });
                chatPane.append($('<h5 />').addClass('last'));
            } else {
                var h2 = $('<h2>No members online at this time</h2>');
                chatPane.append(h2);
            }
        } else {
            var h2 = $('<h2>Sorry, we are unable to load chat list at this time...</h2>');
            chatPane.append(h2);
        }
    };
        var initiateChat = function (member) {
            if (PMChat.ChatEnabled == false) {
                alert('You must enable chat to send and receive messages!');
                return;
            }
            PMChat.Client({
                SiteID: member.SiteId,
                MemberID: member.EncryptedMemberId,
                NickName: member.Username,
                PhotoUrl: member.PhotoUrl
            });
            PMChat.UI.ChatTabFocus({ WithMember: { MemberID: member.EncryptedMemberId } }, true);
        };

    pub.HideChat = function () {
        if (chatPane == null || chatPane.length == 0 || pub.IsEnabled == false || !shouldToggle()) {
            return;
        }
        isShowing = false;
        win.off('scroll');
        win.off('resize');

        columnLeft.animate({ 'margin-left': '0px' }, 400);
        chatPane.animate({ 'right': '-200px' }, 400, function () {
            var h1 = chatPane.find('>h1').clone();
            chatPane.children().remove();
            chatPane.append(h1);
            chatPane.append('<p>Loading Members...</p>');
        });
    };
    var resized = function () {
        var win = $(window);
        var leftColMargin = columnLeft.css('margin-left');
        var width = win.width();
        if (width > 1330) {
            if (leftColMargin != '-95px') {
                columnLeft.animate({ 'margin-left': '-95px' }, 400);
            }
        }
        else if (width > 1280) {
            if (leftColMargin != '-55px') {
                columnLeft.animate({ 'margin-left': '-55px' }, 400);
            }
        } else {
            if (leftColMargin != '-45px') {
                columnLeft.animate({ 'margin-left': '-45px' }, 400);
            }

        }

        scrolled();
    };
    var scrolled = function () {
        var win = $(window);
        var scrollTop = win.scrollTop();

        if (scrollTop > 80) {
            if (chatPane.css('top') == '0') return;
            chatPane.css('top', '0px');
        }
        else if (scrollTop >= 0) {
            chatPane.css('top', 80 - scrollTop + 'px');
        };
    };

    return pub;
})(jQuery);

$jq(document).ready(PeopleMedia.Timer.Init);
$jq(document).ready(PeopleMedia.Popups.Init);
